package com.cskaoyan.catmall.service.Impl;

import com.cskaoyan.catmall.dao.MarketCommentMapper;
import com.cskaoyan.catmall.dao.MarketOrderMapper;
import com.cskaoyan.catmall.dao.MarketUserMapper;
import com.cskaoyan.catmall.model.pojo.*;
import com.cskaoyan.catmall.model.vo.WxUserIndexVo;
import com.cskaoyan.catmall.service.WxUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 创建日期: 2022-01-12-16-13
 * author : LL
 * description:
 */
@Service
public class WxUserServiceImpl implements WxUserService {
    @Autowired
    MarketUserMapper userMapper;

    @Autowired
    MarketOrderMapper  orderMapper;

    @Autowired
    MarketCommentMapper commentMapper;

    @Override
    public void updateUser(HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        MarketUser principal = (MarketUser) subject.getPrincipal();
        principal.setLastLoginIp(request.getRemoteHost());
        principal.setLastLoginTime(new Date());
        userMapper.updateByPrimaryKey(principal);
    }

    @Override
    public WxUserIndexVo getUserIndex(MarketUser principal) {
        int uncomment = 0;
        int unpaid = 0;
        int unrecv = 0;
        int unship = 0;
        MarketOrderExample orderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andUserIdEqualTo(principal.getId());
        criteria.andDeletedEqualTo(false);
        List<MarketOrder> orders = orderMapper.selectByExample(orderExample);
        for (MarketOrder order : orders) {
            if (order.getOrderStatus().equals(101)){
                unpaid++;
            }else if (order.getOrderStatus().equals(201)){
                unship++;
            }else if (order.getOrderStatus().equals(301)){
                unrecv++;
            }
        }
        MarketCommentExample commentExample = new MarketCommentExample();
        MarketCommentExample.Criteria commentCriteria = commentExample.createCriteria();
        commentCriteria.andDeletedEqualTo(false).andUserIdEqualTo(principal.getId()).andTypeEqualTo((byte) 0);
        List<MarketComment> comments = commentMapper.selectByExample(commentExample);
        if (orders.size() > comments.size()){
            uncomment = orders.size()-comments.size();
        }

        WxUserIndexVo userIndexVo = new WxUserIndexVo();
        userIndexVo.setOrder(new WxUserIndexVo.OrderDTO(unrecv,uncomment,unpaid,unship));
        return userIndexVo;
    }
}